package com.wlcb.jpower.chat.server;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.wlcb.jpower.constant.ChatConfigConstant;
import com.wlcb.jpower.module.common.support.EnvBeanUtil;
import com.wlcb.jpower.module.common.utils.Fc;
import com.wlcb.jpower.properties.JpowerChatProperties;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.InetAddress;
import java.util.Properties;

/**
 * @author: liwenfei
 * @desc: 将netty服务注册到nacos
 */
@Slf4j
@Component
public class JpowerChatRegister {

    @Autowired
    private JpowerChatProperties chatProperties;

    @SneakyThrows(NacosException.class)
    private NamingService getNaming() {
        String profiles = EnvBeanUtil.getProfile();
        String serverAddr = EnvBeanUtil.getString("jpower.".concat(profiles).concat(".nacos.server-addr"));
        String namespace = EnvBeanUtil.getString("jpower.".concat(profiles).concat(".nacos.namespace"));
        log.info("获取nacos地址【{}:{}】",serverAddr,namespace);
        Properties properties = new Properties();
        properties.setProperty("serverAddr", serverAddr);
        if (Fc.isNotBlank(namespace)){
            properties.setProperty("namespace", namespace);
        }
        return NamingFactory.createNamingService(properties);
    }

    @SneakyThrows
    public void register() {
        NamingService namingService = getNaming();
        Instance nacosInstace = new Instance();
        nacosInstace.setIp(InetAddress.getLocalHost().getHostAddress());
        nacosInstace.setPort(chatProperties.getServerPort());
        nacosInstace.setHealthy(true);
        nacosInstace.setWeight(1);
        nacosInstace.setEnabled(true);
        namingService.registerInstance(ChatConfigConstant.ChatAppConstant.CHAT_SERVER, nacosInstace);
    }

    @SneakyThrows
    public void stop() {
        NamingService namingService = getNaming();
        namingService.deregisterInstance(ChatConfigConstant.ChatAppConstant.CHAT_SERVER, InetAddress.getLocalHost().getHostAddress(), chatProperties.getServerPort());
    }
}
